package org.jeecg.modules.online.cgform.enhance.impl.http.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RestUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.cgform.entity.OnlCgformEnhanceJava;
import org.jeecg.modules.online.cgform.util.CgformUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * Online表单JavaHttp增强超类
 *
 * @author sunjianlei
 */

public interface CgformEnhanceHttpInter {

    Logger logger = LoggerFactory.getLogger(CgformEnhanceHttpInter.class);

    default int execute(String tableName, JSONObject json, OnlCgformEnhanceJava enhance) {
        return CgformUtil.OL_IMPORT_INSERT;
    }

    default void execute(String tableName, List<Map<String, Object>> dataList, OnlCgformEnhanceJava enhance) {
    }

    default Object sendPost(JSONObject params, OnlCgformEnhanceJava enhance) {
        if (enhance == null) {
            return null;
        }
        String url = enhance.getCgJavaValue();
        if (oConvertUtils.isEmpty(url)) {
            return null;
        }
        // 判断是否不以 http(s) 开头
        if (!url.startsWith("http") && !url.startsWith("https")) {
            String baseUrl = RestUtil.getBaseUrl();
            // 如果url不是以/开头，那就拼接上/
            if (url.startsWith("/")) {
                url = baseUrl + url;
            } else {
                url = baseUrl + "/" + url;
            }
        }
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        HttpHeaders headers = this.getHeaders(request);
        ResponseEntity<String> response = RestUtil.request(url, HttpMethod.POST, headers, null, params, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            String body = response.getBody();
            if (oConvertUtils.isNotEmpty(body)) {
                try {
                    JSONObject res = JSON.parseObject(body);
                    if (res.getBoolean("success")) {
                        return res.get("result");
                    } else {
                        throw new JeecgBootException(res.getString("message"));
                    }
                } catch (JeecgBootException e) {
                    throw e;
                } catch (Exception e) {
                    logger.warn("请求Online表单Java增强http接口时转换数据出错：" + e.getMessage() + "\n body: " + body);
                    throw new JeecgBootException("Online表单Java增强http接口JSON转换失败！");
                }
            }
        }
        return null;
    }

    //get request headers
    default HttpHeaders getHeaders(HttpServletRequest request) {
        HttpHeaders headers = new HttpHeaders();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            Enumeration<String> values = request.getHeaders(key);
            while (values.hasMoreElements()) {
                headers.set(key, values.nextElement());
            }

        }
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 删掉 Accept-Encoding，不使用gzip压缩，否则会导致乱码报错
        headers.remove("Accept-Encoding");
        headers.remove("accept-encoding");
        headers.remove("Accept");
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        return headers;
    }

}
